package com.sztu.shirocore;

import com.sztu.token.JwtToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import java.util.Collection;
import java.util.LinkedList;

public class UserModularRealmAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 判断realms是否为空
        assertRealmsConfigured();

        JwtToken jwtToken=(JwtToken) authenticationToken;
        String loginType= jwtToken.getLoginType().toString();
        // 所有的realms
        Collection<Realm> realms = getRealms();
        // 目标realms
        LinkedList<Realm> typeRealms = new LinkedList<>();
        for(Realm realm:realms){
            if(realm.getName().contains(loginType)){
                typeRealms.add(realm);
            }
        }


        if(typeRealms.size()==1){
            return doSingleRealmAuthentication(typeRealms.get(0),jwtToken);
        }else {
            return doMultiRealmAuthentication(typeRealms,jwtToken);
        }
    }
}
